
import React, { Component } from "react";
import { connect } from "react-redux";
import { Card, Button, Table, Select, Input } from 'antd';
import { PlusCircleOutlined } from "@ant-design/icons"
import { reqProductList, reqProductSearch, reqProductUpdateStatus } from "../../api";
import { PAGE_SIZE } from "../../config";
import { saveProductInfo } from "../../redux/actions/product_action";
const { Option } = Select;

@connect(
    state => ({}),
    {
        saveProductInfo: saveProductInfo
    }
)
class Product extends Component {

    state = {
        productList: [],
        columnsConfig: [
            {
                title: "商品名称",
                dataIndex: "name",
                key: "name",
            },
            {
                title: "商品描述",
                dataIndex: "desc",
                key: "desc"
            },
            {
                align: "center",
                title: "价格",
                dataIndex: "price",
                key: "price",
                render: price => "￥" + price
            },
            {
                align: "center",
                title: "状态",
                key: "status",
                render: item => {
                    let { status, _id } = item;
                    return (
                        <div>
                            <Button
                                type="primary"
                                danger={status === 1}
                                onClick={
                                    () => {
                                        this.buttonOnClickChangeStatus(_id, status)
                                    }
                                }>
                                {status === 1 ? "下架" : "上架"}
                            </Button>
                            <br />
                            <span>{status === 1 ? "在售" : "已下架"}</span>
                        </div>
                    )
                }
            },
            {
                align: "center",
                title: "操作",
                key: "caozuo",
                render: v => {
                    return (
                        <div>
                            <Button type="link" onClick={() => { this.buttonOnClickProductDetail(v) }}>详情</Button>
                            <Button type="link" onClick={() => { this.buttonOnClickProductUpdate(v) }}>修改</Button>
                        </div>
                    )
                }
            }
        ],
        searchType: "productName",
        keyWord: "",
        isSearch: false,
        pageNum: 1,
        pageSize: 0,
        total: 0
    }

    /**
     * 添加商品回调
     */
    buttonOnClickAddProduct = () => {
        this.props.history.push("/admin/products/product/add_update");
    }

    /**
     * 搜索商品回调
     */
    buttonOnClickSearch = () => {
        this.setState({ isSearch: !(this.state.keyWord === "") }, () => {
            this.getProductList();
        })
    }

    /**
     * 修改状态回调
     * @param {要修改状态的商品的id} _id 
     */
    buttonOnClickChangeStatus = async (_id, status) => {
        let result = await reqProductUpdateStatus(_id, (status === 1) ? 2 : 1);
        let { newStatus } = result;
        let newProductList = [...this.state.productList];
        newProductList = newProductList.map((v) => {
            if (v._id === _id) {
                v.status = parseInt(newStatus);
            }
            return v;
        })
        this.setState({ productList: newProductList });
    }

    /**
     * 跳转到商品详情页面
     * @param {商品id} product 
     */
    buttonOnClickProductDetail = (product) => {
        this.props.saveProductInfo(product);
        this.props.history.push(`/admin/products/product/detail/${product._id}`);
    }

    /**
     * 跳转到修改商品页面
     * @param {商品id} productId 
     */
    buttonOnClickProductUpdate = (product) => {
        this.props.saveProductInfo(product);
        this.props.history.push(`/admin/products/product/add_update/${product._id}`);
    }

    /**
     * select切换的回调
     * optionValue是传来的选项的值
     */
    selectOnChange = (optionValue) => {
        this.setState({ searchType: optionValue });
    }

    /**
     * input里的value改变的回调
     * event是事件对象，event.target是input，event.target.value是input输入框里的值
     */
    inputOnChange = (event) => {
        this.setState({ keyWord: event.target.value });
    }

    /**
     * 点击页码进行跳转
     * @param {页码} pNum
     * 还有一个参数是pageSize，这里没有用到 
     */
    paginationOnChange = (pNum) => {
        this.getProductList(pNum)
    }

    /**
     * 获取商品列表，根据state中的isSearch来判断用哪个请求
     */
    getProductList = async (pageNumber = 1) => {
        let { isSearch } = this.state;
        let result
        if (!isSearch) {
            result = await reqProductList(pageNumber, PAGE_SIZE);
        } else {
            let { searchType, keyWord } = this.state
            result = await reqProductSearch(pageNumber, PAGE_SIZE, searchType, keyWord);
        }
        let { list, pageNum, pageSize, total } = result;
        this.setState({ pageNum, pageSize, total, productList: list });
    }

    componentDidMount() {
        this.getProductList();
    }

    render() {
        return (
            <Card
                title={
                    <div>
                        <Select defaultValue="productName" onChange={this.selectOnChange}>
                            <Option value="productName">按名称搜索</Option>
                            <Option value="productDesc">按描述搜索</Option>
                        </Select>
                        <Input allowClear style={{ margin: "0px 10px", width: "20%" }} onChange={this.inputOnChange} />
                        <Button type="primary" onClick={this.buttonOnClickSearch}>
                            搜索
                        </Button>
                    </div>
                }
                extra={
                    <Button type="primary" icon={<PlusCircleOutlined />}
                        onClick={this.buttonOnClickAddProduct}>
                        添加
                    </Button>
                }
            >
                <Table
                    dataSource={this.state.productList}
                    rowKey="_id"
                    columns={this.state.columnsConfig}
                    bordered
                    pagination={
                        {
                            current: this.state.pageNum,
                            total: this.state.total,
                            pageSize: this.state.pageSize,
                            showQuickJumper: true,
                            onChange: this.paginationOnChange
                        }
                    }
                />
            </Card>
        )
    }
}
export default Product;